package com.wbao.dianniu.manager;

import android.content.Context;

import com.wbao.dianniu.http.Batch;
import com.wbao.dianniu.http.Command;
import com.wbao.dianniu.http.HttpUtil;
import com.wbao.dianniu.http.HttpUtil.MyResponse;
import com.wbao.dianniu.listener.ILoginSMSCode;
import com.wbao.dianniu.listener.ILoginSMSCodeListener;
import com.wbao.dianniu.logical.Action;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;

public class LoginSMSCodeManager implements ILoginSMSCode {

    private ILoginSMSCodeListener mListener = null;
    private Context mContext;

    public LoginSMSCodeManager(Context context) {
        mContext = context;
    }

    @Override
    public void getLoginSmsCode(String mobile) {
        // 向平台发送登录请求
        StringEntity stringEntity = null;
        try {
            Command command = new Command();
            command.addAction(Action.LOGIN_SMS_CODE_GET)
                    .addArgs("mobile", mobile);
            stringEntity = new StringEntity(Batch.build().addCommand(command).toJson(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        HttpUtil http = new HttpUtil();
        http.req(mContext, stringEntity, false, new MyResponse() {

            @Override
            public void responseSucess(Object obj) {
                // TODO Auto-generated method stub
                if (null != mListener)
                    mListener.onLoginSmsSuccess();
            }

            @Override
            public void responseFailure(int errorCode, String msg) {
                // TODO Auto-generated method stub
                if (null != mListener)
                    mListener.onLoginSmsFailure(errorCode, msg);
            }
        });
    }

    @Override
    public boolean addLoginSmsCodeListener(ILoginSMSCodeListener listener) {
        mListener = listener;
        return mListener == null ? false : true;
    }

    @Override
    public boolean removeLoginSmsCodeListener(ILoginSMSCodeListener listener) {
        if (null == listener)
            return false;
        mListener = null;
        return true;
    }
}
